package top.hkyzf.study.leetcode.array;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhufeng
 * @version 1.0
 * @date 2022-1-13 22:37
 */
public class 第三大的数_414 {
    public int thirdMax1(int[] nums) {
        // List<Integer> numList = Arrays.stream(nums).boxed().sorted().collect(Collectors.toList());
        NavigableSet<Integer> numSet = new TreeSet<>();
        for (int i : nums) {
            numSet.add(i);
        }
        if(numSet.size() < 3) {
            return numSet.last();
        } else {
            NavigableSet<Integer> descendingSet = numSet.descendingSet();
            int index = 0;
            for (Integer num : descendingSet) {
                if(index == 2) {
                    return num;
                }
                index++;
            }
            return descendingSet.first();
        }
    }

    public int thirdMax(int[] nums) {
        Integer max1 = null;
        Integer max2 = null;
        Integer max3 = null;
        for (int temp : nums) {
            if (max1 == null || max1 < temp) {
                max3 = max2;
                max2 = max1;
                max1 = temp;
            } else if(max1 > temp && (max2 == null || max2 < temp)) {
                max3 = max2;
                max2 = temp;
            } else if(max2 != null && max2 > temp && (max3 == null || max3 < temp)) {
                max3 = temp;
            }
        }
        return max3 == null ? max1 : max3;
    }

    @Test
    public void testThirdMax () {
        int [] nums = new int[]{2,2,3,1};
        int thirdMax = thirdMax(nums);
        System.out.println(thirdMax);
    }
}
